export class MouseListener {
    private static instance: MouseListener | null = null;
    private leftButtonPressed = false;
    private rightButtonPressed = false;
    private currentPosition: { x: number; y: number } = { x: 0, y: 0 };//当前鼠标位置
    private lastPosition = { x: 0, y: 0 }; // 保存鼠标上一次的位置
    private constructor() {
        // 绑定鼠标按下事件
        window.addEventListener('mousedown', (e) => this.onMouseDown(e));
        // 绑定鼠标释放事件
        window.addEventListener('mouseup', (e) => this.onMouseUp(e));
        // 绑定鼠标移动事件
        window.addEventListener('mousemove', (e) => this.onMouseMove(e));
    }

    /**
     * 获取 MouseListener 实例（单例）
     * @returns MouseListener
     */
    public static getInstance(): MouseListener {
        if (this.instance === null) {
            this.instance = new MouseListener();
        }
        return this.instance;
    }

    /**
     * 鼠标按下事件处理
     */
    private onMouseDown(e: MouseEvent) {
        if (e.button === 0) {
            this.leftButtonPressed = true; // 记录左键按下状态
        }
        if (e.button === 2) {
            this.rightButtonPressed = true; // 记录右键按下状态
        }
    }

    /**
     * 鼠标释放事件处理
     */
    private onMouseUp(e: MouseEvent) {
        if (e.button === 0) {
            this.leftButtonPressed = false; // 记录左键释放状态
        }
        if (e.button === 2) {
            this.rightButtonPressed = false; // 记录右键释放状态
        }
    }

    /**
     * 鼠标移动事件处理
     */
    private onMouseMove(e: MouseEvent) {
        this.lastPosition = { ...this.currentPosition };
        this.currentPosition = { x: e.clientX, y: e.clientY }; // 更新鼠标当前位置
    }

    /**
     * 检测左键是否按下
     */
    public isLeftButtonPressed(): boolean {
        return this.leftButtonPressed;
    }

    /**
     * 检测右键是否按下
     */
    public isRightButtonPressed(): boolean {
        return this.rightButtonPressed;
    }

    /**
     * 获取鼠标当前位置
     */
    public getMousePosition(): { x: number; y: number } {
        return this.currentPosition;
    }

    /**
    * 获取上一次的鼠标位置
     */
    public getLastPosition() {
        return this.lastPosition;
    }

    /**
     * 销毁监听器
     */
    public destroy() {
        window.removeEventListener('mousedown', (e) => this.onMouseDown(e));
        window.removeEventListener('mouseup', (e) => this.onMouseUp(e));
        window.removeEventListener('mousemove', (e) => this.onMouseMove(e));
    }
}
